package com.demo.Main.FtpUtil;

import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;

import java.io.*;


/**
 *
 * @author zxc
 *
 * hutool jar包文件上传成功
 *
 */
public class ZxcDemo {
    public static void main(String[] args) {
        String str;
        try (FileInputStream fis = new FileInputStream(new File("localfile/info.json"))){
            str = new String(fis.readAllBytes());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JSONObject json = new JSONObject(str);
        //System.out.println(json);
        check(json);
        sendfile(json);
    }
    public static void check(JSONObject json)
    {
        String s = json.getStr("ip");
        HttpRequest httpRequest = HttpRequest.get(s).timeout(2000);
        HttpResponse execute = httpRequest.execute();
        System.out.println(execute.getStatus());
    }
    public static void sendfile(JSONObject json){
        //指定的服务器地址
        String ip = json.getStr("ip");
        //用户名
        String user = json.getStr("username");
        //密码
        String password = json.getStr("password");
        //服务器端口
        int port = json.getInt("port");
        // 要上传的文件目录
        File file = new File(json.getStr("file"));
        // 服务器保存文件的目录
        String file1 = json.getStr("ftpfile");
        System.out.println(file.exists());
        Ftp ftp = new Ftp(ip,port,user,password);
        ftp.setMode(FtpMode.Passive);
        boolean upload = ftp.upload(" ", file);
        System.out.println(upload);

        try {
            //ftp.cd(""); // 切换到正确的目录
            try (FileInputStream fis = new FileInputStream(file)) {
                System.out.println(file.exists());
                ftp.upload("", file); // 上传文件到FTP服务器
                ftp.close();
            } catch (FileNotFoundException e) {
                throw new RuntimeException("本地文件未找到", e);
            } catch (IOException e) {
                throw new RuntimeException("上传文件失败", e);
            }

            System.out.println("上传成功");
        } finally {
            try {
                ftp.close(); // 关闭FTP连接
            } catch (IOException e) {
                System.out.println("关闭FTP连接失败");
            }
        }

    }

}
